<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\exception\ApiExcetion;
use App\Http\Requests\LoginRequest;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    /**
     * 小程序用户登录
     * @param LoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiExcetion
     */
    public function login(LoginRequest $request){

        $easyWechat=\EasyWeChat::miniProgram();
        $code=$request->get('code');
        $app=$easyWechat->auth->session($code);
        \Log::error('session_key',$app);

        if (!isset($app['openid'])){
            throw new ApiExcetion(json_encode($app));
        }
        $userInfo= UserInfo::where('openid',$app['openid'])->first();
        if (!$userInfo){
            //创建新用户
            $user=new User();
            $user->name=$request->get('nickName');
            $user->password=bcrypt('123456');
            //$user->is_passed=1;
            $user->save();
            $userInfo=new UserInfo();
            $userInfo->user_id=$user->id;
            $userInfo->avatar=$request->get('avatarUrl');
            $userInfo->nickname=$user->name;
            $userInfo->city=$request->get('city');
            $userInfo->province=$request->get('province');
            $userInfo->openid=$app['openid'];
            $userInfo->save();
        }else{
            $user=User::find($userInfo->user_id);
        }

        if(isset($app['unionid'])){
            $user->unionid=$app['unionid'];
        }

        $user->session_key=$app['session_key'];
        $user->save();
       // $user=User::find('10');
        $credentials = ['name' => $user->name, 'id'=>$user->id,'password'=>'123456'];
        if (!$token = auth('api')->attempt($credentials)) {
            throw new ApiExcetion('登录失败');
        }
        return $this->respondWithToken($token,$app);
    }

    /**
     * 业务员退出
     * @authenticated
     */
    public function logout(){
        auth('api')->logout();
        return response()->json(
            [
                'code'=>0,
                'data'=>'退出成功',
            ]
        );
    }

    /**
     * 刷新token
     * @authenticated
     */
    public function refresh(){
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token,$app='')
    {
        return response()->json([
            'status' => 1,
            'message'=>'请求数据成功',
            'data' => [
                'access_token' => $token,
                'token_type' => 'bearer',
                'session_key'=>$app['session_key'],
                'expires_in' => auth('api')->factory()->getTTL() * 6000
            ]
        ]);
    }
}
